<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="queryParams" class="demo-form-inline" label-width="auto">
      <el-form-item label="成本单据号" prop="projectNo">
        <el-input v-model="queryParams.billsNo" placeholder="请输入单据号" clearable @keyup.enter="handleQuery"
          v-hasPermi="['system:bills:query']" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery" v-hasPermi="['system:bills:query']">搜索</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据展示表格 -->
    <el-row :gutter="10" class="mb8">
      <!-- 操作行 -->
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:bills:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="Upload" v-if="false" @click="handleUpload">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" v-if="false" @click="handleExport">导出</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" v-show="!multiple" @click="handleDelete">批量删除</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="tableData" style="width: 100%" :border="true" max-height="500"
      :header-cell-style="{
        background: '#cccccc!important',
        height: '100px',
        color: '#000000',
        display: 'none',
      }">
      <el-table-column>
        <template #default="props">
          <div style="
              display: flex;
              flex-direction: row;
              justify-content: space-between;
            ">
            <div>
              <p style="padding: 5px">单据编号:{{ props.row.billsNo }}</p>
            </div>
            <div>
              <el-button link type="primary" icon="Edit" @click="handleUpdate(props.row)"
                v-hasPermi="['system:bills:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(props.row)"
                v-hasPermi="['system:bills:remove']">删除</el-button>
            </div>
          </div>
          <el-table :data="props.row.costBills" :border="childBorder" :header-cell-style="{
            height: '100px',
            color: '#000000',
            padding: 0,
            marginBottom: '10px',
          }">
            <el-table-column label="项目编号" prop="projectNo" width="155" />
            <el-table-column label="井号（简称）" prop="shortNo" width="155" />
            <el-table-column label="结算月份" prop="settlementMonth" width="155" />
            <el-table-column label="施工天数" prop="constructionDays" width="100" />
            <el-table-column label="施工队名称" prop="deptThreeName" width="155" />
            <el-table-column label="付款单位" prop="paymentdeptName" width="155" />
            <el-table-column label="主观停等天数" prop="subjectivityWaitingDays" width="155" />
            <el-table-column label="客观停等天数" prop="objectiveWaitingDays" width="155" />
            <el-table-column label="停等原因" prop="reason" width="155" />
            <el-table-column label="总成本" prop="totalCost" width="155" />

            <el-table-column label="成本费用明细">
              <el-table-column :prop="item.subjectName" :label="item.subjectName" width="200" v-for="(item, index) in props.row.costBills[0].children.map(
                (e) => e
              )">
                <template #default="scope">
                  {{ scope.row.children.find(fitem => item.subjectId == fitem.subjectId).cost }}
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 新增修改弹框 -->
    <el-dialog :title="title" v-model="open" width="80vw" append-to-body>
      <el-form :inline="true" ref="postRef" :rules="rules" :model="formData" label-width="80px">
        <el-form-item prop="projectType">
          <el-button type="primary" @click="typeopen = true">请选择项目类别</el-button>
        </el-form-item>
        <el-form-item prop="wellNo">
          <el-button type="primary" @click="openSubSelect">请选择费用明细</el-button>
        </el-form-item>
      </el-form>

      <el-table :border="true" :data="DiatableData" style="width: 100%" fit>
        <el-table-column width="120">
          <template #default="scope">
            <el-button v-if="scope.row.wellNo == '合计' ? false : true" size="small" type="danger"
              @click="deleteRow(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column v-for="(item, index) in DiatableListA" :key="index" :prop="item.prop" :label="item.label"
          width="120" />
          <el-table-column prop="settlementMonth" label="结算月份" width="240">
            <template #default="scope">
              <el-date-picker v-if="scope.row.wellNo == '合计' ? false : true" v-model="scope.row.settlementMonth"
                type="month" placeholder="请选择结算月份" format="YYYY/MM" value-format="YYYY-MM" size="small" />
            </template>
          </el-table-column>

        <el-table-column prop="subjectivityWaitingDays" label="主观停等天数" width="150">
          <template #default="scope">
            <el-input-number v-model="scope.row.subjectivityWaitingDays" :min="0" size="small" controls-position="right"
              :disabled="scope.row.wellNo == '合计'" />
          </template>
        </el-table-column>
        <el-table-column prop="objectiveWaitingDays" label="客观停等天数" width="150">
          <template #default="scope">
            <el-input-number v-model="scope.row.objectiveWaitingDays" :min="0" size="small" controls-position="right"
              :disabled="scope.row.wellNo == '合计'" />
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="停等原因" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.reason" :min="0" size="small" controls-position="right"
              :disabled="scope.row.wellNo == '合计'" />
          </template>
        </el-table-column>

        <el-table-column prop="constructionDays" label="施工天数" width="150">
          <template #default="scope">
            <el-input-number v-model="scope.row.constructionDays" :min="0" size="small" controls-position="right"
              @change="DaysumNum(scope.row)" :disabled="scope.row.wellNo == '合计'" />
          </template>
        </el-table-column>
        <el-table-column prop="sharingCoefficient" label="分摊系数" width="150">
          <template #default="scope">
            <el-input-number v-model="scope.row.sharingCoefficient" :precision="4" :min="0" size="small"
              controls-position="right" disabled />
          </template>
        </el-table-column>
        <el-table-column v-for="(item, index) in DiatableListB" :key="index" :prop="item.prop" :label="item.label"
          width="150">
          <template #default="scope">
            <el-input-number v-if="scope.row.wellNo == '合计'
              ? scope.row.costInfoList[index].distribution == '1'
                ? true
                : false
              : true
              " v-model="scope.row.costInfoList[index].cost" :min="0" :precision="4" @change="typesumNum(scope.row)"
              size="small" controls-position="right" :disabled="scope.row.wellNo == '合计'
                ? scope.row.costInfoList[index].distribution == '1'
                  ? false
                  : true
                : scope.row.costInfoList[index].distribution == '1'
                  ? true
                  : false
                " />
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增修改内部选择科目分类弹框 -->
    <subjectDialog v-model:open="subDialogOpen"></subjectDialog>
    <!-- 新增修改内部选择项目分类弹框 -->
    <projectDialog v-model:open="typeopen"></projectDialog>
  </div>
</template>

<script setup>
import { ref, reactive, provide } from "vue";
import { ElLoading } from 'element-plus'
import {
  listManagement,
  getManagement,
  addManagement,
  updateManagement,
  listtypeManagement,
  delManagement,
  listSub,
  listTwoDept,
  listPaydept,
} from "@/api/cost/bills";

import subjectDialog from "./components/subjectDialog.vue";
import projectDialog from "./components/projectDialog.vue";
import { pinyin } from "pinyin-pro";
// import subjectDialog from '@/views/cost/bills/components/subjectDialog'
// 字典引入
const { proxy } = getCurrentInstance();
const { payment_type, construction_flag } = proxy.useDict(
  "payment_type",
  "construction_flag"
);
//新增修改表格数据
const DiatableData = ref([
  {
    wellNo: "合计",
    sharingCoefficient: 1,
    costInfoList: [
      {
        cost: 0,
      },
    ],
  },
]);
const Dataformarr = ref([]);

// 科目选择
const subDialogOpen = ref(false);

//项目选中暂存数组
const selectProject = ref([]);
provide('selectList', selectProject)
//科目选中暂存数组
const selectSubOption = ref([]);
provide('selectSubOption', selectSubOption)

//定义已有的科目列表，方便后续添加到项目中
const latestSubject = ref([]);

//新增修改表格表头
const DiatableListA = ref([
  {
    prop: "wellNo",
    label: "井号",
  },
  {
    prop: "deptThreeName",
    label: "施工单位",
  },
  {
    prop: "constructionAddress",
    label: "施工地点",
  },
  {
    prop: "constructionContent",
    label: "施工内容",
  },
  {
    prop: "startTime",
    label: "开工日期",
  },
]);
const DiatableListB = ref([]);
//部门下拉树
const queryPaydeptList = ref();
// 表格数据
const tableData = ref([]);
const loading = ref(true);
// 数据总数
const total = ref(0);
//打开弹框
const open = ref(false);
const typeopen = ref(false);

const title = ref();
const update = ref(true);

// 删除的ids
const ids = ref([]);
// 单选
const single = ref(true);
// 多选
const multiple = ref(true);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  wellNo: "",
  billsNo: "",
});
// 项目列表
const projectinfoList = ref([]);
// 表单字段
const formData = ref({
  billsNo: "",
  constructionDays: 0,
  costInfoList: [
    {
      accountId: "",
      accountName: "",
      billsNo: "",
      cost: "",
      createBy: "",
      createTime: "",
      id: "",
      params: {},
      projectNo: "",
      remark: "",
      subjectId: "",
      subjectName: "",
      sysOrgCode: "",
      updateBy: "",
      updateTime: "",
    },
  ],
  proInfoList: [],
  deptId: "",
  id: 0,
  objectiveWaitingDays: "",
  params: {},
  projectNo: "",
  reason: "",
  settlementMonth: "",
  sharingCoefficient: "",
  subjectivityWaitingDays: "",
  sysOrgCode: "",
  totalCost: 0,
  wellNo: "",
});
// 表单规则
const rules = ref({
  settlementMonth: [{ required: true, message: "结算月份不能为空", trigger: "blur" }],
})
// 表单重置
const reset = () => {
  selectProject.value = [];
  selectSubOption.value = [];
  DiatableListB.value = [];
  DiatableData.value = [
    {
      wellNo: "合计",
      sharingCoefficient: 1,
      costInfoList: [
        {
          cost: 0,
        },
      ],
    },
  ];

  formData.value = {
    id: null,
    costInfoList: [],
    projectNo: null,
    wellNo: null,
    shortNo: null,
    projectType: null,
    deptId: null,
    startTime: null,
    completeMonth: null,
    constructionId: null,
    sysOrgCode: null,
    constructionName: null,
    constructionAddress: null,
    constructionContent: null,
    paymentdeptId: null,
    paymentdeptName: null,
    updateBy: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    deptThreeId: null,
    deptThreeName: null,
  };
  proxy.resetForm("postRef");
};
const resetTableData = () => {
  DiatableData.value = [
    {
      wellNo: "合计",
      sharingCoefficient: 1,
      costInfoList: [...latestSubject.value],
    },
  ];
}
onMounted(() => {
  proxy.$bus.on("commitColumn", (params) => {
    putSubColum(params);
  });
  proxy.$bus.on("commitRow", (params) => {
    putProject(params);
  });
});
//获取列表数据
const getList = () => {
  loading.value = true;
  listManagement(queryParams.value)
    .then((res) => {
      tableData.value = res.rows;
      total.value = res.total;
      loading.value = false;
    })
    .catch((error) => {
      console.log(error);
    });
  // 查询框付款单位
  listPaydept().then((res) => {
    queryPaydeptList.value = res.rows;
  });
};
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增";
  update.value = false;
}

//选择项目之后
const putProject = (data) => {
  const existingProjects = DiatableData.value.filter(project => {
    return data.some(newProject => newProject.projectNo === project.projectNo);
  });
  const newProjects = data.filter(newProject => {
    return !existingProjects.some(project => project.projectNo === newProject.projectNo);
  });

  DiatableData.value = DiatableData.value.filter((project, index) => {
    return index === DiatableData.value.length - 1 || existingProjects.some(existingProject => existingProject.projectNo === project.projectNo);
  });
  console.log( latestSubject.value);
  newProjects.forEach((project) => {
    project.costInfoList = JSON.parse(JSON.stringify(latestSubject.value));
  });
  selectProject.value = [...existingProjects, ...newProjects];
  // 更新表格数据
  DiatableData.value = [...selectProject.value, DiatableData.value[DiatableData.value.length - 1]];
}

//点击选择科目
const openSubSelect = () => {
  if (selectProject.value != "") {
    subDialogOpen.value = true;
  } else {
    proxy.$modal.msgError("请优先选择项目");
  }
};

//选择科目之后
const putSubColum = (subData) => {
  const subDataArray = Object.values(subData).map(item => {
    return {
      ...item,
      subjectId: item.id,
      id: undefined
    };
  });
  selectSubOption.value = JSON.parse(JSON.stringify(subDataArray));

  // 表格每一行数据添加选择的科目 
  DiatableData.value = DiatableData.value.map((item) => {
    const existingCostInfoList = item.costInfoList.filter(costInfo => {
      return subDataArray.some(subData => subData.subjectId === costInfo.subjectId);
    });
    const newCostInfoList = subDataArray.filter(subData => {
      return !existingCostInfoList.some(costInfo => costInfo.subjectId === subData.subjectId);
    });
    return {
      ...item,
      costInfoList: [...existingCostInfoList, ...newCostInfoList],
    };
  });

  // 清空原有的科目列 
  DiatableListB.value = [];

  // 添加列 
  addColumn(subDataArray);
};

//添加科目列
const addColumn = (data) => {
  latestSubject.value = JSON.parse(JSON.stringify(data));
  data.forEach((item) => {
    DiatableListB.value.push({
      label: item.subjectName,
      prop: "typeid",
    });
  });
};

//施工天数数字输入框触发方法
function DaysumNum(data) {
  let sum = 0;
  const tableData = DiatableData.value;

  for (let i = 0; i < tableData.length - 1; i++) {
    const item = tableData[i];
    if (item.wellNo !== "合计") {
      sum += item.constructionDays;
    }
  }

  const totalCount = tableData.length;
  const lastItem = tableData[totalCount - 1];
  lastItem.constructionDays = sum;

  for (let i = 0; i < totalCount - 1; i++) {
    const item = tableData[i];
    if (item.wellNo !== "合计") {
      item.sharingCoefficient = item.constructionDays / sum;
    }
  }
  recalculateValues();
}
//及时修改各科目钱数
const recalculateValues = () => {
  const tableData = DiatableData.value;
  const lastItem = tableData[tableData.length - 1];

  for (let i = 0; i < tableData.length - 1; i++) {
    const item = tableData[i];
    if (item.wellNo !== "合计") {
      const sharingCoefficient = item.sharingCoefficient;
      for (let j = 0; j < item.costInfoList.length; j++) {
        if (item.costInfoList[j].distribution == "1") {
          item.costInfoList[j].cost =
            lastItem.costInfoList[j].cost * sharingCoefficient;
        }
      }
    }
  }
};

// 循环数字输入框触发方法
const typesumNum = (inputRow) => {
  if (inputRow.wellNo === "合计") {
    for (var i = 0; i < DiatableData.value.length; i++) {
      const newRow = JSON.parse(JSON.stringify(DiatableData.value[i])); // 创建一个新的对象，使用深拷贝复制属性值
      for (let j = 0; j < newRow.costInfoList.length; j++) {
        if (newRow.costInfoList[j].distribution == 1) {
          newRow.costInfoList[j].cost = inputRow.costInfoList[j].cost * newRow.sharingCoefficient;
        }
      }
      DiatableData.value[i] = newRow; // 将新的对象赋值回原数组
    }
  }
};
//删除一行
const deleteRow = (rowIndex) => {
  selectProject.value.splice(rowIndex, 1)
  DiatableData.value.splice(rowIndex, 1);
  DaysumNum();
  recalculateValues();
};

/** 编辑按钮操作 */
const handleUpdate = async (row) => {
  reset();
  formData.value.billsNo = row.billsNo;
  const loadingInstance = ElLoading.service()
  await getManagement(row.billsNo).then((resProject) => {
    // 获取列
    addColumn(resProject.data[0].costInfoList);
    selectSubOption.value = JSON.parse(JSON.stringify(resProject.data[0].costInfoList))
    selectProject.value = JSON.parse(JSON.stringify(resProject.data))
    //赋值表格数据
    resProject.data.forEach((item) => {
      DiatableData.value.unshift(item);
    });
    // 计算合计行
    const totalRow = DiatableData.value[DiatableData.value.length - 1];
    computeTotal(totalRow, resProject.data[0].costInfoList, resProject.data);

    open.value = true;
    title.value = "修改";
    update.value = true;
    loadingInstance.close()
  });
};

//计算合计行
const computeTotal = (totalRow, costList, numberList) => {
  // 将 costList 赋值给 totalRow 的 costinforlist 字段
  totalRow.costInfoList = JSON.parse(JSON.stringify(costList));
  const costInfoList = numberList.flatMap(number => number.costInfoList);
  totalRow.costInfoList.forEach(item => {
    let sum = 0
    costInfoList.forEach(cost => {
      if (cost.subjectId === item.subjectId) {
        sum += parseFloat(cost.cost)
      }
    })
    item.cost = sum
  })
};
//计算每一行的total
const countTotal=()=>{
  DiatableData.value.forEach(item=>{
    let sum = 0
    item.costInfoList.forEach(costs=>{
      sum+=costs.cost
    })
    item.totalCost = sum
  })

}
// 提交
const submitForm = () => {
  countTotal()
  const loadingInstance = ElLoading.service()
  Dataformarr.value = [];
  DiatableData.value.pop();
  DiatableData.value.forEach((item) => {
    const {
      billsNo,
      constructionDays,
      costInfoList,
      proInfoList,
      deptId,
      objectiveWaitingDays,
      params,
      projectNo,
      reason,
      settlementMonth,
      sharingCoefficient,
      subjectivityWaitingDays,
      sysOrgCode,
      totalCost,
      wellNo,
    } = item;
    const NewObj = {
      billsNo,
      constructionDays,
      costInfoList,
      proInfoList,
      deptId,
      objectiveWaitingDays,
      params,
      projectNo,
      reason,
      settlementMonth,
      sharingCoefficient,
      subjectivityWaitingDays,
      sysOrgCode,
      totalCost,
      wellNo,
    };
    NewObj.billsNo = formData.value.billsNo;
    Dataformarr.value.push(NewObj);
  });
  Dataformarr.value.forEach((item) => {
    item.costInfoList = item.costInfoList.map((items) => {
      const {
        accountId,
        accountName,
        cost,
        subjectId,
        subjectName,
        distribution,
        sysOrgCode,
        redgerType,
      } = items;
      const newobj = {
        accountId,
        accountName,
        cost,
        subjectId: items.subjectId || items.id,
        subjectName,
        distribution,
        sysOrgCode,
        redgerType,
      };
      return newobj;
    });
  });
  proxy.$refs["postRef"].validate((valid) => {
    if (valid) {
      if (update.value) {
        updateManagement(Dataformarr.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
          loadingInstance.close()

        });
      } else {
        addManagement(Dataformarr.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
          loadingInstance.close()

        });
      }
    }

  });
};

// 取消
const cancel = () => {
  open.value = false;
};
/** 删除按钮操作 */
function handleDelete(row) {
  const delId = row.billsNo || ids.value;
  proxy.$modal.confirm('是否确认删除?').then(function () {
        return delManagement(delId);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
  // delManagement(delId).then((res) => {
  //   getList();
  // });
}
/**导出按钮操作 */
function handleExport() {
  proxy.download(
    "/system/management/export",
    {
      ...queryParams.value,
    },
    `项目列表.xlsx`
  );
}

//查询列表
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

getList();
</script>

<style lang="scss" scoped>
.el-row {
  margin-bottom: 20px;
}

.search-form {
  padding-left: 20px;
}

.el-width {
  width: 340px;
}
</style>
